package com.antler.smt.admin.service.impl;

import com.antler.smt.admin.mapper.*;
import com.antler.smt.constant.CashConstant;
import com.antler.smt.constant.DateTimeConstant;
import com.antler.smt.entity.*;
import com.antler.smt.enums.ResultCodeEnum;
import com.antler.smt.request.admin.GetRequirementListReq;
import com.antler.smt.request.base.BasePageReq;
import com.antler.smt.response.admin.*;
import com.antler.smt.response.base.Result;
import com.antler.smt.service.admin.ManageVipService;
import com.antler.smt.utils.DateUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * vip管理实现接口 TODO
 *
 * @author zhangyi
 * @date 2018/4/19 10:06
 */
@Service
public class ManageVipServiceImpl implements ManageVipService {

    @Autowired
    private PurchaserInfoMapper purchaserInfoMapper;

    @Autowired
    private PurchaserEntityMapper purchaserEntityMapper;

    @Autowired
    private RequirementInfoMapper requirementInfoMapper;

    @Autowired
    private PurchaserAccountInfoMapper purchaserAccountInfoMapper;

    @Autowired
    private RequirementEntityMapper requirementEntityMapper;

    @Autowired
    private PurchaserCashCouponEntityMapper purchaserCashCouponEntityMapper;

    @Autowired
    private PurchaserCashCouponInfoMapper purchaserCashCouponInfoMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private MemberEntityMapper memberEntityMapper;

    @Autowired
    private SupplierEntityMapper supplierEntityMapper;

    @Autowired
    private PurchaserAccountEntityMapper purchaserAccountEntityMapper;

    @Autowired
    private PurchaserChargeInfoMapper purchaserChargeInfoMapper;

    @Autowired
    private UserEntityMapper userEntityMapper;

    /**
     *  整体管理Vip信息列表
     *
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<Page<GetPurchaserVipInfoListResp>> manageVipList(BasePageReq request,List<Integer> list) {
        Result result = null;
        PageHelper.startPage(request.getPageCurrent(), request.getPageSize());
        Page<GetPurchaserVipInfoListResp> purchaserInfoList = purchaserInfoMapper.getPurchaserInfoList(list);

        for(int i = 0; i < purchaserInfoList.size(); i++){
            GetPurchaserVipInfoListResp purchaserList = purchaserInfoList.get(i);
            //获取其订单数量
            GetRequirementListReq requirementListReq = new GetRequirementListReq();
            requirementListReq.setPurchaserId(purchaserList.getId());

            List<GetRequirementListResp> requirementList = requirementInfoMapper.listRequirementInfo(requirementListReq);

            //获取订单数量
            long size = requirementList.size();
            PurchaserAccountEntity purchaserAccount =
                    purchaserAccountInfoMapper.selectPurchaserAccountByMemberId(purchaserList.getMemberId());

            if(purchaserAccount != null) {
                purchaserInfoList.get(i).setVipAndCount("v" + purchaserAccount.getVipLevel()
                        + "/" + purchaserAccount.getCashCoupon() + "张");
            }else {
                purchaserInfoList.get(i).setVipAndCount("暂无");
            }

            //后台实际审核的总金额
            Long totalMoney = purchaserChargeInfoMapper.getTotalMoney(purchaserList.getId());
            purchaserInfoList.get(i).setTotalMoney(totalMoney);
            //添加最后一次审核的金额
            Long lastAuditResult = purchaserChargeInfoMapper.getLastAuditResult(purchaserList.getId());
            purchaserInfoList.get(i).setLastMoney(lastAuditResult);

            purchaserInfoList.get(i).setOrderCount(size);
        }

        if (purchaserInfoList != null) {
            PageInfo<GetPurchaserVipInfoListResp> listPage = new PageInfo(purchaserInfoList);
            result = new Result(listPage);
        } else {
            result = new Result(ResultCodeEnum.QUERY_DATA_ERROR, "查询数据为空！");
        }
        return result;
    }

    /**
     * 获取此采购商所有订单列表
     *
     * @param id
     * @return
     */
    @Override
    public Result<PageInfo<GetOrderListResp>> orderCount(Long id,BasePageReq request) {
        Result result = null;
        PurchaserEntity purchaserEntity = purchaserEntityMapper.selectByPrimaryKey(id);

        PageHelper.startPage(request.getPageCurrent(), request.getPageSize());
        Page<GetOrderListResp> orderListResps = orderInfoMapper.selectOrderByMember(purchaserEntity.getMemberId());

        for (int i = 0; i < orderListResps.size(); i++){
            MemberEntity memberEntity = null;
            RequirementEntity requirementEntity = null;
            //服务商id
            Long supplierId = orderListResps.get(i).getSupplierId();
            SupplierEntity supplierEntity = supplierEntityMapper.selectByPrimaryKey(supplierId);
            if(supplierEntity != null) {
                GetOrderListResp o = orderListResps.get(i);
                memberEntity = memberEntityMapper.selectByPrimaryKey(supplierEntity.getMemberId());
                requirementEntity  = requirementEntityMapper.selectByPrimaryKey(orderListResps.get(i).getRequirementId());

                orderListResps.get(i).setCompanyName(supplierEntity.getCompanyName());
                orderListResps.get(i).setNickName(memberEntity.getNickName());
                orderListResps.get(i).setName(requirementEntity.getName());
                UserEntity userEntity = userEntityMapper.selectByPrimaryKey(o.getConnectUserId());
                if(userEntity != null) {
                    orderListResps.get(i).setRealName(userEntity.getRealName());
                }
            }

        }
        if (orderListResps != null) {
            PageInfo<GetOrderListResp> listPageInfo = new PageInfo(orderListResps);
            result = new Result(listPageInfo);
        } else {
            result = new Result(ResultCodeEnum.QUERY_DATA_ERROR, "获取此采购商所有订单列表为空！");
        }
        return result;
    }

    /**
     *  冻结用户操作
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> freeze(Long id,Integer status) {
        Result result = null;

        //创建用户实体
        MemberEntity memberEntity = new MemberEntity();

        PurchaserEntity purchaserEntity = purchaserEntityMapper.selectByPrimaryKey(id);
        //插入主键id
        memberEntity.setId(purchaserEntity.getMemberId());
        //插入状态
        memberEntity.setStatus(status);
        int i = memberEntityMapper.updateByPrimaryKeySelective(memberEntity);
        result = (0 == i ? new Result(ResultCodeEnum.APPEND_DATA_ERROR):new Result(ResultCodeEnum.OPERATION_SUCCESS));
        return result;
    }

    /**
     * 发放代金券
     *
     * @param id
     * @param cashLists 发放代金券的列表 价值的列表
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> provideCashCoupon(Long id,List<Integer> cashLists) {

        Result result = null;

        //获取当前时间模型
        Calendar calendar = Calendar.getInstance();

        //获取当前时间
        Date localtime = calendar.getTime();

        //发放代金券，此时代金券有效期是从现在算起6个月过期
        calendar.add(Calendar.MONTH,6);

        //设置6个月后的时间
        Date sixMonth = calendar.getTime();

        //定义时间格式
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //创建采购商代金券实体
        PurchaserCashCouponEntity purchaserCashCouponEntity = new PurchaserCashCouponEntity();

        //采购商实体
        PurchaserEntity purchaserEntity = purchaserEntityMapper.selectByPrimaryKey(id);

        int i = 0;

        for (Integer money : cashLists){

            //添加此时发放的日期
            purchaserCashCouponEntity.setCreateTime(DateUtil.stampToDate(localtime.getTime()));

            //添加过期的日期
            purchaserCashCouponEntity.setEndTime(DateUtil.stampToDate(sixMonth.getTime()));

            //添加会员id
            purchaserCashCouponEntity.setMemberId(purchaserEntity.getMemberId());

            //添加价值
            purchaserCashCouponEntity.setValue(money);

            //添加创建时间
            purchaserCashCouponEntity.setCreateTime(DateUtil.stampToDate(System.currentTimeMillis()));
            purchaserCashCouponEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

            i = purchaserCashCouponEntityMapper.insertSelective(purchaserCashCouponEntity);
        }
        //采购商的会员账户
        Long memberId = purchaserEntity.getMemberId();
        //采购商的账户
        PurchaserAccountEntity purchaserAccountEntity = purchaserAccountInfoMapper.selectPurchaserAccountByMemberId(memberId);
        //开始代金券的数量
        Integer cashCoupon = purchaserAccountEntity.getCashCoupon();
        //重新设置代金券的数量
        purchaserAccountEntity.setCashCoupon(cashCoupon+cashLists.size());
        //设置更新日期
        purchaserAccountEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        int i1 = purchaserAccountEntityMapper.updateByPrimaryKeySelective(purchaserAccountEntity);
        if(0 == (i&i1)){
            result = new Result(ResultCodeEnum.MODIFY_DATA_ERROR,"方法代金券失败！");
        }else{
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        }
        return result;
    }

    /**
     * 获取有效代金券列表
     *
     * @param id 采购商id
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<GetPurchaserCashCouponListResp> cashCouponInfo(Long id) {
        Result result = null;

        PurchaserEntity purchaserEntity = purchaserEntityMapper.selectByPrimaryKey(id);

        List<GetPurchaserCashCouponListResp> getPurchaserCashCouponListResps = purchaserCashCouponInfoMapper.selectCashByMemberId(purchaserEntity.getMemberId());

        //新的代金卷列表
        List<GetPurchaserCashCouponListResp> purchaserCashCouponList = new ArrayList<>();

        //判断此采购商的代金卷是否过期（根据时间）
        for (GetPurchaserCashCouponListResp pcl:getPurchaserCashCouponListResps){

            //获取此代金券的截止时间
            Date endTime = pcl.getEndTime();

            //获取此代金券的创建时间
            Date createTime = pcl.getCreateTime();

            //结束毫秒数
            long endTimeCount = endTime.getTime();

            //开始毫秒数
            long createTimeCount  = createTime.getTime();

            //判断时间是否过期
            if (endTimeCount - createTimeCount <=0){
                continue;
            }else{
                purchaserCashCouponList.add(pcl);
            }
        }

        result = new Result(purchaserCashCouponList);

        return result;
    }

    /**
     * 作废代金券
     *
     * @param cashCouponId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> cancelCashCoupon(Long cashCouponId) {
        Result result = null;

        PurchaserCashCouponEntity purchaserCashCoupon = purchaserCashCouponEntityMapper.selectByPrimaryKey(cashCouponId);

        //减少代金券的数量
        PurchaserAccountEntity purchaserAccountEntity =
                purchaserAccountInfoMapper.selectPurchaserAccountByMemberId(purchaserCashCoupon.getMemberId());

        //目前此采购商所拥有的代金券
        Integer cashCoupon = purchaserAccountEntity.getCashCoupon();
        if(cashCoupon > 0) {
            purchaserAccountEntity.setCashCoupon(cashCoupon - 1);
        }else{
            purchaserAccountEntity.setCashCoupon(0);
        }

        purchaserAccountEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        //更新代金券数量的日期
        int i = purchaserAccountEntityMapper.updateByPrimaryKeySelective(purchaserAccountEntity);

        //创建采购商代金券
        PurchaserCashCouponEntity purchaserCashCouponEntity = new PurchaserCashCouponEntity();
        //设置id
        purchaserCashCouponEntity.setId(cashCouponId);
        //设置代金券的作废日期 到期日期为初始时间，代金券作废
        Date endTime = purchaserCashCoupon.getCreateTime();
        purchaserCashCouponEntity.setEndTime(endTime);
        purchaserCashCouponEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        int i1 = purchaserCashCouponEntityMapper.updateByPrimaryKeySelective(purchaserCashCouponEntity);
        if(0 == (i1 & i)){
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR,"代金券作废失败！");
        }else{
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        }
        return result;
    }

    /**
     *  获取所要发放的代金券的列表
     *
     * @return
     */
    @Override
    public Result showCashCoupon() {
        Result result = null;

        Object[] cashArray = null;
        List<Object> list = new ArrayList<>();

        //20代金券
        cashArray = new Object[2];
        cashArray[0] = CashConstant.PRICE_20;
        cashArray[1] = CashConstant.PRICE_20_DESC;
        list.add(cashArray);

        //80代金券
        cashArray = new Object[2];
        cashArray[0] = CashConstant.PRICE_80;
        cashArray[1] = CashConstant.PRICE_80_DESC;
        list.add(cashArray);

        //200代金券
        cashArray = new Object[2];
        cashArray[0] = CashConstant.PRICE_200;
        cashArray[1] = CashConstant.PRICE_200_DESC;
        list.add(cashArray);

        //300代金券
        cashArray = new Object[2];
        cashArray[0] = CashConstant.PRICE_300;
        cashArray[1] = CashConstant.PRICE_300_DESC;
        list.add(cashArray);

        //500代金券
        cashArray = new Object[2];
        cashArray[0] = CashConstant.PRICE_500;
        cashArray[1] = CashConstant.PRICE_500_DESC;
        list.add(cashArray);

        //1000代金券
        cashArray = new Object[2];
        cashArray[0] = CashConstant.PRICE_1000;
        cashArray[1] = CashConstant.PRICE_1000_DESC;
        list.add(cashArray);

        //2000代金券
        cashArray = new Object[2];
        cashArray[0] = CashConstant.PRICE_2000;
        cashArray[1] = CashConstant.PRICE_2000_DESC;
        list.add(cashArray);

        //后期 待 添加代金券
        result = new Result(list);

        return result;
    }
}
